import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/controller/imageDetailVideoController.dart';
import 'package:qianyi/entity/search/SearchResult.dart';
import 'package:qianyi/state/token.dart';

import '../../../../../controller/homeTabController.dart';
import '../../../../../network/http_config.dart';
import '../../../../../network/http_manager.dart';
import '../../../../../ui/widget/custom_refresh.dart';
import '../../../../../utils/throttle.dart';
import '../../../../../view_model/searcher/search_result_model.dart';




class SearchPage2 extends StatefulWidget {

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage2> {
  TokenController tokenController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find();
  HomeTabController homeTabController = Get.find();
  final FocusNode focusNode = FocusNode();
  final TextEditingController _searchController = TextEditingController();
  SearchResultViewModel? viewModel;
  List<Map<String, dynamic>> items = [
    {'title': '绝美风景，一次看个够', 'author': 'qwer', 'likes': 2},
    {'title': '绝美风景，一次看个够', 'author': 'qwer', 'likes': 2},
    {'title': '美女', 'author': 'qwer', 'likes': 99},
    {'title': '夕阳之美', 'author': 'qwer', 'likes': 2},
  ];
@override
  void initState() {


    // TODO: implement initState
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: TextField(
          focusNode: focusNode,
          controller: _searchController,
          decoration: InputDecoration(hintText: "搜索"),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search, color: Colors.black), // 搜索图标颜色
            onPressed: () async {
              HudUtil.showBeautiful(context);
              focusNode.unfocus();

              if(_searchController.text.length <= 0) {
                return;
              }
              Map<String,dynamic> params ={"uid":tokenController.uid,"keyword":_searchController.text};
               HttpManager.getInstance().request(url: '/platform/searchRecord/addSearchRecord',method: Method.post,params: params);
               HttpManager.getInstance().request(url: '/search/searchRecord/addSearchRecordData',method: Method.get,params: params);


              homeTabController.searchName = _searchController.text;

              _searchController.clear();
              viewModel!.onRefresh();

              // Get.toNamed("/view_model/find/searcher");
            },
          ),
        ],
      ),
      body: ChangeNotifierProvider(
          create: (BuildContext context) => SearchResultViewModel(),
          child: Consumer<SearchResultViewModel>(
              builder: (context, viewModel, child) {
                this.viewModel = viewModel;
                return CustomRefresh(

                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,

                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child: buildView(viewModel)
                  ,


                );
              })
      )
      ,
    );
  }

  buildView(SearchResultViewModel viewModel) {
  return ListView.builder(
    itemCount: viewModel.datas.length,
    itemBuilder: (BuildContext context, int index) {
      SearchResult item = viewModel.datas[index];
      return GestureDetector(
        onTap: () async {
          HudUtil.showBeautiful(context);
          String uid = await tokenController.getUid();
          Map<String,dynamic> params = {
            "mid":item.id,
            "uid": uid
          };
          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
          imageDetailVideoController.imageDetailId.value = item.id!;
          await imageDetailVideoController.getImageVideoDetail();
          HudUtil.dismiss();
          Get.toNamed("/ui/home/imageVideoDetail");
        },
        child: Card(
          margin: EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
              item.cover != null ? FancyShimmerImage(imageUrl: item.cover!):Image.asset('assets/kg.jpg'), // Placeholder image
              ListTile(
                title: Text(maxLines:5,item.content!),
                subtitle: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(item.username!),
                    Row(
                      children: <Widget>[
                        Icon(Icons.star_border),
                        Text('${item.collectionCount}'),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
      )
        ;
    },
  );
  }
}
